package com.wyg.servlet;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mysql.jdbc.PreparedStatement;
import com.wyg.jdbc.JDBCTamplate;
import com.wyg.jdbc.Jdbc;
import com.wyg.jdbc.PreparedStatementSetter;

/**
 * Servlet implementation class CarServlet
 */
@WebServlet("/CarServlet")
public class CarServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CarServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
		request.setCharacterEncoding("utf-8");
		
		String xinghao = request.getParameter("xinghao");
		Float baojia =Float.parseFloat(request.getParameter("baojia"));
		
		String sql1 = "SELECT * FROM usershopcar WHERE xh='"+xinghao+"'";
		Jdbc.getConnection();
		ResultSet rs = Jdbc.query(sql1);
		try {
			if(rs.next()){
				response.setHeader("fmessage", "1");
			}else{
				response.setHeader("fmessage", "2");
				String sql2="INSERT INTO usershopcar VALUES(?,?,1)";
				JDBCTamplate jt = new JDBCTamplate(Jdbc.conn);
				jt.insert(sql2,new PreparedStatementSetter(){

					@Override
					public void setValues(java.sql.PreparedStatement pstmt) {
						// TODO Auto-generated method stub
						try {
							pstmt.setString(1, xinghao);
							pstmt.setFloat(2, baojia);
						} catch (SQLException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					
				});
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
